package com.example.mvp_demo.presenter;

import android.os.Handler;
import android.os.Message;

import com.example.mvp_demo.data.Phone;
import com.example.mvp_demo.moudle.PhoneFactory;
import com.example.mvp_demo.view.OperationView;

import java.util.ArrayList;

/**
 * Created by Administrator on 2017/3/23.
 * presenter层,处理界面逻辑和数据模型
 */

public class PhonePresenter implements TaskPresenter{

    private final PhoneFactory phoneFactory;
    private final OperationView operationView;

    private static final long createPhoneTime=2000;
    private static final int msgWhat = 0x102;

    //构造器
    public PhonePresenter(PhoneFactory phoneFactory, OperationView operationView) {
        this.phoneFactory = phoneFactory;
        this.operationView = operationView;
    }


    @Override
    public void addPhone(Phone phone) {
        operationView.showPhoneCountChange();
        if (mHandler.hasMessages(msgWhat)){
            operationView.showFactoryBusy();
            return;
        }
        Message message = new Message();
        message.what = msgWhat;
        message.obj = phone;
        mHandler.sendMessageDelayed(message,createPhoneTime);
        operationView.showCreatingPhone();
    }

    @Override
    public void removePhone(Phone phone) {

    }

    @Override
    public void removePhone(int index) {
        phoneFactory.removePhone(index);
        if (phoneFactory.getPhoneCount()<=0){
            operationView.showNoPhone();
        }
        operationView.showPhoneCountChange();
    }

    public ArrayList<Phone> getPhones(){
        ArrayList<Phone> phones = phoneFactory.getPhoneList();
        if (phones.isEmpty()){
            operationView.showNoPhone();
        }
        return phones;
    }


    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

        }
    };
}
